package cn.tedu.calendar.service.impl;

import cn.tedu.calendar.mapper.CalendarMapper;
import cn.tedu.calendar.pojo.dto.CalendarParam;
import cn.tedu.calendar.pojo.dto.CalendarQuery;
import cn.tedu.calendar.pojo.entity.Calendar;
import cn.tedu.calendar.pojo.vo.CalendarVO;
import cn.tedu.calendar.service.CalendarService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class CalendarServiceImpl implements CalendarService {
    @Autowired
    private CalendarMapper calendarMapper;
    @Override
    public List<CalendarVO> selectByUserId(Long userId) {
        return calendarMapper.selectByUserId(userId);
    }

    @Override
    public List<CalendarVO> selectByDates(CalendarQuery calenderQuery) {
        Calendar calender = new Calendar();
        calender.setUserId(calenderQuery.getUserId());

        List<CalendarVO> calenderVos = new ArrayList<>();
        for(Date date : calenderQuery.getDates()){
            calender.setDayTime(date);
            calenderVos.addAll(calendarMapper.selectByData(calender));
        }

        return calenderVos;
    }

    @Override
    public void saveMemo(CalendarParam calendarParam) {
        log.debug("传入到服务端的参数{}",calendarParam);
        Calendar calender = new Calendar();
        //多个memo通过\n截取
        String[]  contents = calendarParam.getContent().split("\n");

        BeanUtils.copyProperties(calendarParam,calender);
        //获取中间间隔的天数
        long betweenDays = TimeUnit.MILLISECONDS.toDays(calendarParam.getEndTime().getTime()
                - calendarParam.getStartTime().getTime());

        //新增备忘
        if(calendarParam.getIds().trim().isEmpty()){
            //根据日期的天数，循环新增备忘录
            for(int index=0; index <= betweenDays; index++){
                //根据新增的备忘数据
                for(int indexCol = 0; indexCol < contents.length; indexCol++){
                    calender.setContent(contents[indexCol]);
                    calender.setDayTime(changeDay(calendarParam.getStartTime(),index));//转换成对应date数据
                    calendarMapper.insertMemo(calender);
                }

            }
        }else{
            //修改备忘,根据日期的天数，循环新增备忘录
            //多个id通过\n截取
            String[] StringIds = calendarParam.getIds().split("\n");
            Long[] ids = new Long[StringIds.length];

            try {
                for(int index = 0; index < StringIds.length; index++){
                    ids[index] = Long.parseLong(StringIds[index]);
                    log.debug("修改的备忘id{}",ids[index]);
                }
            } catch (NumberFormatException e) {
                log.debug("字符串id转不能换成Long类型");
                throw new RuntimeException(e.getMessage());
            }

            int idIndex = 0;
            for(; idIndex <ids.length; idIndex++){
                log.debug("---------进入修改的数据{}",calendarParam);
                calender.setId(ids[idIndex]);
                calender.setDayTime(calendarParam.getStartTime());
                if(!contents[idIndex].trim().isEmpty()){
                    log.debug("修改后的备忘内容{}",contents[idIndex]);
                    calender.setContent(contents[idIndex]);
                    calendarMapper.updateMemo(calender);
                }else {
                    log.debug("删除后的备忘内容2{}",contents[idIndex]);
                    //如果修改后的字符串未"",则表示需要删除该字符串
                    calender.setId(ids[idIndex]);
                    calendarMapper.deleteMemo(calender.getId());
                }
            }

            //如果id的下标小于备忘事件数组的长度，说明，除了有修改的备忘录，改天还有新增的备忘录
            if(idIndex < contents.length){
                log.debug("是否需要重新添加{}",idIndex);
                for(int index=idIndex; index < contents.length; index++){
                    //创建新的calender，因为前面有设置calender.setId
                    Calendar calenderNew = new Calendar();
                    calenderNew.setDayTime(calendarParam.getStartTime());
                    calenderNew.setContent(contents[index]);
                    calenderNew.setUserId(calendarParam.getUserId());
                    calendarMapper.insertMemo(calenderNew);
                }
            }
        }
    }


    /**
     * 将原始日期+间隔天数=具体的某天日期
     * @param day 开始的日期
     * @param days 间隔的天数
     * @return 距离开始日期，间隔n天之后的具体Date类型数据
     */
    private Date changeDay(Date day,int days){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //添加天数
        try {
            return sdf.parse(sdf.format(day.getTime() + (long)days*24*60*60*1000));
        } catch (Exception e) {
            /////////////////////////////////////////////////////这里的异常需要处理
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteMemo(Long id) {
        calendarMapper.deleteMemo(id);
    }
}
